package com.yuyang.gulimall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuyang.common.constant.WareConstants;
import com.yuyang.common.utils.PageUtils;
import com.yuyang.common.utils.Query;
import com.yuyang.common.utils.R;
import com.yuyang.gulimall.ware.dao.PurchaseDao;
import com.yuyang.gulimall.ware.entity.PurchaseDetailEntity;
import com.yuyang.gulimall.ware.entity.PurchaseEntity;
import com.yuyang.gulimall.ware.entity.WareInfoEntity;
import com.yuyang.gulimall.ware.entity.WareSkuEntity;
import com.yuyang.gulimall.ware.feign.ProductFeignService;
import com.yuyang.gulimall.ware.service.PurchaseDetailService;
import com.yuyang.gulimall.ware.service.PurchaseService;
import com.yuyang.gulimall.ware.service.WareSkuService;
import com.yuyang.gulimall.ware.vo.PurchaseDoneItemVO;
import com.yuyang.gulimall.ware.vo.PurchaseDoneVo;
import com.yuyang.gulimall.ware.vo.PurchaseMergeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageListUnreceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new LambdaQueryWrapper<PurchaseEntity>().
                        eq(PurchaseEntity::getStatus, WareConstants.PurchaseStatusEnum.CREATED.getCode()).
                        or().eq(PurchaseEntity::getStatus, WareConstants.PurchaseStatusEnum.ASSIGNED.getCode())
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public R mergePurchaseDetail(PurchaseMergeVO purchaseMergeVO) {
        Long purchaseId = purchaseMergeVO.getPurchaseId();
        Integer assignedCode = WareConstants.PurchaseDetailStatusEnum.ASSIGNED.getCode();
        Integer createdCode = WareConstants.PurchaseDetailStatusEnum.CREATED.getCode();
        PurchaseEntity purchase = new PurchaseEntity();
//        Date date = new Date();
//        purchase.setCreateTime(date);
//        purchase.setUpdateTime(date);

        List<Long> purchaseDetailIds = purchaseMergeVO.getItems();
        List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listByIds(purchaseDetailIds);
        for (PurchaseDetailEntity purchaseDetailEntity : purchaseDetailEntities) {
            Integer status = purchaseDetailEntity.getStatus();
            if (!status.equals(assignedCode) && !status.equals(createdCode)){
                return R.error("请选择新建或者已分配的采购需求");
            }
        }
        //创建新的采购单
        if (purchaseId == null) {
            purchase.setStatus(WareConstants.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchase);
            purchaseId = purchase.getId();
        } else {

            //分配采购项，修改采购项状态和更新采购单时间
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> collect = purchaseDetailEntities.stream().
                    peek(purchaseDetailEntity -> {
                        purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                        if (purchaseDetailEntity.getStatus().equals(createdCode)){
                            purchaseDetailEntity.setStatus(assignedCode);
                        }
                    }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);

//            LambdaUpdateWrapper<PurchaseEntity> lambdaUpdateWrapper = new LambdaUpdateWrapper<PurchaseEntity>().
//                    set(PurchaseEntity::getUpdateTime, date).
//                    eq(PurchaseEntity::getId, purchaseId);
//            this.update(lambdaUpdateWrapper);
        }
        return R.ok();
    }

    @Transactional
    @Override
    public void receivedPurchase(List<Long> purchaseIds) {
        //修改采购单的状态为已领取
        List<PurchaseEntity> purchaseEntities = this.listByIds(purchaseIds);
        List<PurchaseEntity> collect = purchaseEntities.stream().filter(item -> item.getStatus() == WareConstants.PurchaseStatusEnum.ASSIGNED.getCode()).
                peek(item -> item.setStatus(WareConstants.PurchaseStatusEnum.RECEIVED.getCode())).
                collect(Collectors.toList());
        this.updateBatchById(collect);

        //修改采购项的状态为正在采购
        List<Long> ids = collect.stream().map(PurchaseEntity::getId).collect(Collectors.toList());
        LambdaUpdateWrapper<PurchaseDetailEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(PurchaseDetailEntity::getStatus,WareConstants.PurchaseStatusEnum.RECEIVED.getCode()).
                in(PurchaseDetailEntity::getPurchaseId,ids);
        purchaseDetailService.update(updateWrapper);

    }
    @Transactional
    @Override
    public void finishPurchase(PurchaseDoneVo purchaseDoneVo) {
        //1、修改采购项状态
        Integer haserrorCode = WareConstants.PurchaseDetailStatusEnum.HASERROR.getCode();
        Integer finishedCode = WareConstants.PurchaseDetailStatusEnum.FINISHED.getCode();
        boolean flag = true;
        List<PurchaseDoneItemVO> items = purchaseDoneVo.getItems();
        List<PurchaseDetailEntity> purchaseDetailEntityList = new ArrayList<>();
        for (PurchaseDoneItemVO item : items) {
            Long itemId = item.getItemId();
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(itemId);
            if (item.getStatus() == haserrorCode) {
                flag = false;
                purchaseDetailEntity.setStatus(haserrorCode);
            } else {
                purchaseDetailEntity.setStatus(finishedCode);
                //2、成功采购的商品加入仓库
                PurchaseDetailEntity byId = purchaseDetailService.getById(itemId);
                wareSkuService.addOrUpdateStock(byId.getSkuId(), byId.getWareId(), byId.getSkuNum());
            }
            purchaseDetailEntityList.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(purchaseDetailEntityList);

        //3、修改采购单状态
        PurchaseEntity purchase = new PurchaseEntity();
        purchase.setId(purchaseDoneVo.getId());
        purchase.setStatus(flag?WareConstants.PurchaseStatusEnum.FINISHED.getCode():WareConstants.PurchaseStatusEnum.HASERROR.getCode());
        this.updateById(purchase);
    }
}